<template>
  <el-col :span="24" class="comment">
    <div class="add-ramark" @click.stop="showRemarkDiv">
      <i class="iconfont icon-beizhu"></i><span @click="showRemarkDiv">{{$t('public.addRemarks')}}</span>
    </div>
    <div v-show="isshow">
      <!--<header>-->
        <!--<h3>{{$t('business.businessRemark')}}</h3>-->
      <!--</header>-->
      <main style="padding-top: 5px;">
        <div class="comment-input" ref="input" contenteditable="true" @keydown="keyIn">
        </div>
        <div ref="treeWrap" v-show="atShow" v-if="atShow !== null" class="at-tree" :style=pos>
          <agent-tree ref="agentTree" @saveFollowedAgents="saveAtAgents" :showCheckbox="false"></agent-tree>
        </div>
        <div class="wrapper">
          <el-button @click.stop="cancel"  class="primary_btn">{{$t('public.cancel')}}</el-button>
          <el-button type="primary" @click.stop="excuteBusinessComentAction" class="primary_btn">{{$t('public.save')}}</el-button>
        </div>
      </main>
    </div>
  </el-col>
</template>
<script>
  import BTextarea from './base/Btextarea.vue'
  import AgentTree from './agentTree'
  import {getCurrentDateTime} from '@/utils/m7Utils'
  import { position } from 'caret-pos'
  import {trim, uniq} from 'lodash'
  import * as types from '@/store/modules/business/mutation-types.js'
  export default {
    name: 'businessComment',
    props: {
      tabName: String,
      business: Object
    },
    components: {
      BTextarea,
      AgentTree
    },
    data () {
      return {
        form: {
          _id: this.business._id,
          backInfo: '',
          atAgents: []
        },
        isshow: false,
        clear: '',
        pos: {
          left: '15px',
          top: '30px'
        },
        lastSelection: {},
        atShow: null // 默认值为null，不加载agentTree组件，当输入@后才加载
      }
    },
    watch: {
      business () {
        this.isshow = false
        this.form._id = this.business._id
      }
    },
    methods: {
      saveAtAgents ({_id, label}) {
        this.$refs.input.focus()
        this.atShow = false
        // 获取之前保留先来的信息。
        // 需要修改 keyIn 的代码，保存选区以及光标信息，用于获取在光标焦点离开前，光标的位置
        let selection = this.lastSelection.selection
        let range = this.lastSelection.range
        let textNode = range.startContainer
        // 删除 @ 符号。
        range.setStart(textNode, range.endOffset)
        range.setEnd(textNode, range.endOffset + 1)
        range.deleteContents()

        // 生成需要显示的内容，包括一个 span 和一个空格。
        let spanNode1 = document.createElement('span')
        let spanNode2 = document.createElement('span')
        spanNode1.className = 'at-text'
        spanNode1.id = _id
        spanNode1.setAttribute('contenteditable', false)
        spanNode1.innerHTML = '@' + label.split(' ')[0]
        spanNode2.innerHTML = '&nbsp;'
        this.form.atAgents.push(_id)
        // 将生成内容打包放在 Fragment 中，并获取生成内容的最后一个节点，也就是空格。
        let frag = document.createDocumentFragment()
        let node
        let lastNode
        frag.appendChild(spanNode1)
        while ((node = spanNode2.firstChild)) {
          lastNode = frag.appendChild(node)
        }
        // 将 Fragment 中的内容放入 range 中，并将光标放在空格之后。
        range.insertNode(frag)
        selection.extend(lastNode, 1)
        selection.collapseToEnd()
      },
      keyIn (e) {
        let selection = window.getSelection()
        if (e.code === 'Digit2' && e.shiftKey) {
          // 输入@
          if (this.$refs.agentTree) {
            // 重置坐席树
            this.$refs.agentTree.resetAgent()
          }
          // debugger
          let {left, top} = position(this.$refs.input)
          // let offsetData = offset(this.$refs.input)
          // let windowWidth = document.documentElement.clientWidth
          let inputWidth = this.$refs.input.clientWidth
          if (this.$refs.treeWrap) {
            if (left + 33 > inputWidth) {
              // 光标在当前行的最后位置时
              this.pos.left = '15px'
              this.pos.top = top + 45 + 'px'
            } else if (left + 270 < inputWidth) {
              // 右侧没有超出window宽度时
              this.pos.left = left + 'px'
              this.pos.top = top + 25 + 'px'
            } else {
              // 右侧有超出window宽度时
              this.pos.left = inputWidth - 270 + 'px'
              this.pos.top = top + 25 + 'px'
            }
          }
          this.atShow = true
          // 保存光标信息
          this.lastSelection = {
            range: selection.getRangeAt(0),
            offset: selection.focusOffset,
            selection: selection
          }
        } else if (this.atShow) {
          this.atShow = false
        } else if (e.code === 'Backspace') {
          // 删除逻辑
          // 1 ：由于在创建时默认会在 @xxx 后添加一个空格，
          // 所以当得知光标位于 @xxx 之后的一个第一个字符后并按下删除按钮时，
          // 应该将光标前的 @xxx 给删除
          // 2 ：当光标位于 @xxx 中间时，按下删除按钮时应该将整个 @xxx 给删除。
          let range = selection.getRangeAt(0)
          var removeNode = null
          if (range.startOffset <= 1 && range.startContainer.nodeName === '#text' && range.startContainer.parentElement.className === 'comment-input') {
            removeNode = range.startContainer.previousElementSibling
          }
          if (range.startContainer.parentElement.className === 'at-text') {
            removeNode = range.startContainer.parentElement
          }
          if (removeNode) {
            let id = removeNode.id
            let index = this.form.atAgents.indexOf(id)
            if (index !== -1) {
              this.form.atAgents.splice(index, 1)
            }
            this.$refs.input.removeChild(removeNode)
          }
        }
      },
      cancel () {
        this.isshow = false
      },
      excuteBusinessComentAction () {
        let backInfo = trim(this.$refs.input.innerText)
        if (!backInfo) {
          this.$message.error('备注内容必填')
          return
        }
        this.form.backInfo = uniq(this.form.backInfo)
        this.form.backInfo = backInfo
        this.$store.dispatch('addBusinessBackInfo', this.form).then(() => {
          this.isshow = false
//          this.$emit('event', {event: 'commentAction', data: {_id: this.business._id, customer: this.business.customer}})
          let data = {
            'businessId': this.business._id,
            'step': this.business.step,
            'action': 'comment',
            'excuteData': {
              'backInfo': this.form.backInfo
            },
            'time': getCurrentDateTime(),
            'master': this.$store.state.session.user._id
          }
          this.$store.commit(types.ADD_BUSINESS_ACTION_HISTORY, {data})
        })
      },
      showRemarkDiv () {
        this.isshow = true
        this.form.atAgents = []
        this.$refs.input.innerHTML = ''
      }
    },
    mounted () {
    },
    beforeMount () {
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../../assets/common.styl'
  .comment
    padding 20px 0 0
  header
    padding 10px 0
    text-align center
    h3
      display inline-block
      color $cf-gray1
  main
    position: relative
    .at-tree
      position absolute
      width:270px
      box-sizing border-box
      padding 10px
      border: 1px solid $c-border1
      z-index 6
      border-radius 3px
      background-color #fff
    .el-col
      margin-top 20px
    &:after
      content ''
      display block
      clear both
    .wrapper
      float right
      margin-top 5px
  .add-ramark
    cursor pointer
    display inline-block
    color $cf-gray1
    .iconfont
      fontsize 20px
      margin-right 5px
      color $c-main
  .comment-input
    height 72px
    overflow-y scroll
    border 1px solid $c-border1
    padding 5px 15px
    border-radius 3px
    margin-bottom 10px
  .at-text
    color $c-pink
</style>
